package com.huilai.platform.country_platform.service;

import com.huilai.platform.country_platform.core.Result;
import com.huilai.platform.country_platform.core.ResultGenerator;
import com.huilai.platform.country_platform.model.ChatList;
import com.huilai.platform.country_platform.model.User;
import com.huilai.platform.country_platform.repository.ChatListReposity;
import com.huilai.platform.country_platform.repository.UserRepository;
import com.huilai.platform.country_platform.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 作者：洪霓
 * 日期：2023/2/13
 * 注释：
 */
@Service
public class LoginService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ChatListReposity chatListReposity;

    public Result login(User user, HttpServletResponse response, HttpSession session) {
        User userByUsername = userRepository.findUserByUsername(user.getUsername());
        if (userByUsername == null) {
            return ResultGenerator.genFailResult("用户名错误!");
        } else {
            if (user.getPassword().equals(userByUsername.getPassword())) {

                Cookie cookie = new Cookie("username", user.getUsername());
                cookie.setPath("/");
                cookie.setMaxAge(3600);
                response.addCookie(cookie);
                session.setAttribute("user", user);
//                System.out.println(session.getAttribute("user").getClass());
                return ResultGenerator.genSuccessResult();
            } else {
                return ResultGenerator.genFailResult("密码错误!");
            }
        }
    }
    public void logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Cookie cookie = CookieUtil.get(request, "username");
        if (cookie != null) {
//            User userByUsername = userRepository.findUserByUsername(cookie.getValue());
//            chatListReposity.updateFromWindow(userByUsername.getId(), 0);
//            chatListReposity.updateToWindow(userByUsername.getId(), 0);
            CookieUtil.set(response, "username", null, 0);
        }
        session.setAttribute("user", null);
    }

    public Result register(User user) {
        User userByUsername = userRepository.findUserByUsername(user.getUsername());
        if(userByUsername != null){
            return ResultGenerator.genFailResult("用户名重复!");
        }
//        user.setId(IdGenerator.id());
        userRepository.save(user);
        return ResultGenerator.genSuccessResult();
    }

}
